package com.itheima_03;

public class BinarySearchDemo1 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        int num =4;
        int index = BinarySearch(arr,num);
        System.out.println(index);
    }

    public static int BinarySearch(int[] arr,int num) {
        int max = arr.length -1;//最大索引为length-1
        int min = 0;//最小索引为0
        while (max>=min){
            int mid = (max+min)>>1;//中间索引(max+min)/2
            if (arr[mid]>num){ //如果中间值大于查找值,那么目标值在左边123
                max=mid-1;
            }else if(arr[mid]<num){//如果中间值小于目标值,那么目标值在右边
                min=min+1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
